<template>
  <view>
    <view class="search">
      <view class="title">
        <view>最近搜索</view>
        <uni-icons type="trash" size="25" @click="clear"/>
      </view>
      <view>
        <view class="name"
              v-for='(item,index) in searchList' :key="index" @click="selectHistory(item)">{{item}}</view>
      </view>

    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      keyword:'',
      searchList:[],
    }
  },
  // 监听点击搜索
  onNavigationBarButtonTap(e) {
    this.search()
  },
  // 获取搜索框value
  onNavigationBarSearchInputChanged(e) {
    this.keyword = e.text;

  },
  // 软键盘搜索
  onNavigationBarSearchInputConfirmed() {
    this.search()
  },
  // 读取搜索历史
  mounted() {
    uni.getStorage({
      key: 'search',
      success: (res)=>{
        this.searchList = JSON.parse(res.data)
      }
    })
  },
  methods: {
    // 选中历史搜索项，将其填入搜索框
    selectHistory(item) {
      this.keyword = item; // 将选中的历史搜索项赋值给搜索框输入值
      this.search()
    },

    // 搜索框判断不能为空
    search(){
      if (this.keyword =='') {
        return uni.showToast({
          title:'关键词不能为空',
          icon:'none'
        })
      }
      // 收起软键盘
      uni.hideKeyboard();
      this.addSearch();
      uni.navigateTo({
        url: '/pages/product/prodList/index?keyword=' + this.keyword,
      });

    },
    // 存储搜索历史
    addSearch(){
      this.searchList.unshift(this.keyword);  //搜索的历史置顶
      this.searchList = Array.from(new Set(this.searchList))  //去重
      uni.setStorage({
        key:'search',
        data: JSON.stringify(this.searchList),
      })
    },
    // 清除搜索历史
    clear(){
      uni.removeStorage({
        key: 'search',
      });
      this.searchList=[];
    },
    setCurrentSearch(item) {
    },
  }
}
</script>

<style scoped lang="scss">
.search{
  display: flex;
  flex-direction: column;
  padding: 20rpx;
  .title{
    display: flex;
    justify-content: space-between;

    text{
      font-size: 40rpx;

    }
  }
  .name{
    display: inline-block;
    background: #f1f1f1;
    color: orangered;
    border-radius: 30rpx;
    padding: 10rpx 20rpx;
    font-size: 28rpx;
    margin: 10rpx;
  }
}
</style>